package com.molyfun.parents.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.telephony.TelephonyManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 工具类
 * @author ligang
 *
 */
public class Tools {

	/**
	 * 实体类解码
	 *
	 * @param object
	 * @throws Exception
	 */
	public static void decode(Object object) {
		try {
			if (object != null) {
				Class cls = object.getClass();
				Field[] fields = cls.getDeclaredFields();
				for (int i = 0; i < fields.length; i++) {
					Field f = fields[i];
					f.setAccessible(true);
//				System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(object));
					Class type = f.getType();
					if (type == String.class) {
						if (f.get(object) != null) {
							f.set(object, URLDecoder.decode("" + f.get(object), "utf-8"));
						}
					} else if (type == List.class) {
						List<Object> list = (ArrayList) f.get(object);
						if (list != null && list.size() > 0) {
							for (Object o : list) {
								decode(o);
							}
						}
					}
//				System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(object));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从sdcard上读一个文件
	 * @param filePath
	 * @return
	 */
	public static byte[] readFileFromSdcard(String filePath) {
		byte[] data = null;
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(filePath);
			int size = fileInputStream.available();
			data = new byte[size];
			fileInputStream.read(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fileInputStream != null) {
				try {
					fileInputStream.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return data;
	}
	/**
	 * 向sdcard写数据
	 * @param context
	 * @param path
	 * @param fileName
	 * @param data
	 */
	public static void writeToSdcard(Context context, String path,
									 String fileName,byte[] data) {
		FileOutputStream fileOutputStream = null;
		try {
			// 判断sdcard的状态
			String sdcardState = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
				// MOUNTED有sdcard
				// 判断path有没有
				File filePath = new File(path);
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				// 判断file有没有
				File file = new File(path, fileName);
				if (file.exists()) {
					file.delete();
				}
				// 写数据
				fileOutputStream = new FileOutputStream(file);
				fileOutputStream.write(data);
				fileOutputStream.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fileOutputStream != null)
					fileOutputStream.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

	}
	/**
	 * 获取文件的路径
	 * @return
	 */
	public static String getFilePath(Context context, Uri uri) {
		String filePath = null;
		if ("content".equalsIgnoreCase(uri.getScheme())) {
			Cursor cursor = context.getContentResolver().query(uri,
					new String[] { Images.Media.DATA }, null, null, null);
			if (null == cursor) {
				return null;
			}
			try {
				if (cursor.moveToNext()) {
					filePath = cursor.getString(cursor.getColumnIndex(Images.Media.DATA));
				}
			} finally {
				cursor.close();
			}
		}
		// 从文件中选择
		if ("file".equalsIgnoreCase(uri.getScheme())) {
			filePath = uri.getPath();
		}

		return filePath;
	}

	/**
	 * 根据日期字符串算出时间戳
	 * @param timeStr 日期字符串
	 * @return	时间戳
	 * @throws ParseException
	 */
	public static long getTimestampByTimestr(String timeStr){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date date=null;
		try {
			date=sdf.parse(timeStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date.getTime();
	}

	/**
	 * 根据出生时间戳算年龄年月日
	 * @param birthdatetime 出生时间戳
	 * @return 年月日
	 */
	public static String getAgeForBirthday(long birthdatetime){
		if (birthdatetime==0) {
			return "未知年龄";
		}
		long time=System.currentTimeMillis()-birthdatetime;
		int days=  (int) Math.abs(time/1000/60/60/24);
		int year=days/365;
		int month=(days-year*365)/30;
		int day=days-year*365-month*30;
		return year+"年"+month+"月"+day+"天";
	}

	/**
	 * Returns unique UUID of the device
	 * @param context Context
	 * @return UUID
	 */
	public static UUID getDeviceUUID(Context context) {
		UUID uuid=null;
		TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		String id = tm.getDeviceId();
		if (id != null) {
			uuid = UUID.nameUUIDFromBytes(id.getBytes());
		}
		return uuid;
	}

	/**
	 * 随机生成十位大写字母
	 * @return
	 */
	public static String randomCapital() {
		String capital = "";
		char[] ziMu = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
				'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z' };
		for (int i = 0; i < 10; i++) {
			int x = (int) (Math.random() * 26);
			capital = capital + ziMu[x];
		}
		return capital;
	}

	/**
	 * 自然排序 进行sha-1加密
	 * @param nonce 客户端随机生成十位的大写字母
	 * @param timestamp 当前秒的时间戳
	 * @param token "MOLYFUN-GAMECOLLECTION"
	 * @return signature
	 */
	public static String checkSignature(String nonce, String timestamp, String token) {
		String[] arr = new String[] { nonce, timestamp, token };
		// 将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;
		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		content = null;
		return tmpStr;
	}
	/**
	 * 将字节数组转换为十六进制字符串
	 *
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}
	/**
	 * 将字节转换为十六进制字符串
	 *
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];
		String s = new String(tempArr);
		return s;
	}

	/**
	 * 返回当前程序版本名
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versionName;
	}


}
